<script lang="ts" setup>
import type { TablePaginationConfig, DrawerProps,  } from 'ant-design-vue';
import { $t } from '@vben/locales';
import { preferences } from '@vben/preferences';
import type { MinishopOrder, MinishopOrderResponse } from './types.ts';
import type { ProductInfos } from './hometypes.ts';
import type { MinishopOrderDetail, MinishopOrderDetailResponse } from '../minishop_order_detail/types.ts';
import type { MinishopCart, MinishopCartResponse } from '../minishop_cart/types.ts';
import type { ComponentSetting, ComponentSettingResponse } from '../../uctoo/component_setting/types.ts';
import { onMounted, reactive, ref, computed, nextTick,type Ref } from 'vue';
import { message, InputNumber, notification } from 'ant-design-vue';
import editform from './edit.vue';
import { useRoute, useRouter } from 'vue-router';
import { removeEmpty } from '#/utils/common';
import { uctoo_minishop_spu,  uctoo_component_setting, uctoo_minishop_cart, uctoo_minishop_order, uctoo_wechatpay_transaction } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { useTabs } from '@vben/hooks';

// import Swiper bundle with all modules installed
import Swiper from 'swiper/bundle';
// import styles bundle
import 'swiper/css/bundle';
import { formatPrice } from '#/utils/common';
import VueQrcode from 'vue-qrcode';
import { generateClientId, getDomainName } from '#/utils/common';
const client_id = ref("");
const router = useRouter();
// 获取当前路由信息
const route = useRoute();
// 获取查询字符串部分
let queryParam = reactive({ ...route.query });
const currentDatas = ref<MinishopOrder[]>([]);
const currentRecord = ref<MinishopOrder | null>(null);
const currentCart = ref<MinishopCart | null>(null);
const headimgs = ref<string[]>([]);
const descInfo = ref<string[]>([]);
const quantity = ref(1);
const final_price = ref(0);
const order_id = ref('');
const order_title = ref('订单名称');
const payUrl = ref<string>('https://www.uctoo.com');
const showPayQrCode = ref(false);
const orderDetail = ref<MinishopOrderDetail | null>(null);
const product_infos = ref<ProductInfos[] | null>(null);
const payOperator = ref<'wechatpay' | 'wechatpayJSAPI' | 'alipay'>('wechatpayJSAPI'); //支付接口提供商
const qrText = ref<string>('https://www.uctoo.com');
const qrOptions = ref({
  width: 200,
  margin: 2,
  colorDark: '#000000',
  colorLight: '#ffffff'
});
const { closeCurrentTab } = useTabs();

const minishopSpuRepo = computed(() => {
  return useRepo(uctoo_minishop_spu)
});
const minishopCartRepo = computed(() => {
  return useRepo(uctoo_minishop_cart)
});
const minishopOrderRepo = computed(() => {
  return useRepo(uctoo_minishop_order)
});

const cancelOrder = async () => {
  await useAxiosRepo(uctoo_minishop_order).api().edituctooMinishopOrder({ status: 250, id: order_id.value });
  closeCurrentTab();
};

const payOrder = async () => {
  
  await initWebSocket();
  
  //如果是需要物流的订单，此页面必填用户地址信息，后端生成address_info_id再提交支付

  //根据用户选择的不同支付方式，提交不同的支付参数
  if(payOperator.value == 'wechatpay'){
    console.log('提交的数据:', currentRecord.value)
    const res = await useAxiosRepo(uctoo_wechatpay_transaction).api().payTransactionsH5(currentRecord.value)
    console.log('支付信息:', res.response)
    if (res && res.response.data.order_id) {
      
      // 调起微信支付
      //window.location.href = res.response.data.h5_url;
      showPayQrCode.value = true;
      payUrl.value = res.response.data.h5_url;
     
    } else {
      message.error('调起微信支付操作失败');
    }
  }
  if(payOperator.value == 'wechatpayJSAPI'){ //如涉及到用户登录态的订单，微信JSAPI支付需要根据当前登录用户的token传入user_type=uctoo_user | wechatopen_users | wechatopen_miniapp_users ，不涉及可不传
    payUrl.value = import.meta.env.VITE_WEBSITE_DOMAIN + '/unipay/unipay-wechatjssdk?order_id=' + currentRecord.value?.id + '&client_id=' + client_id.value;//加client_id跳转到unipay收银台的二维码
    if (payUrl.value) {
      showPayQrCode.value = true;
      // 扫码调起JSAPI微信支付
     // websocket接收订单支付成功通知
     
    } else {
      message.error('调起微信支付操作失败');
    }
  }
  
}
const increaseQuantity = () => {
  quantity.value++
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// WebSocket消息类型
interface WebSocketMessage {
  type: 'message' | 'system'
  content: string
  timestamp: number
  clientId?: string
}

// 响应式状态
const isConnected: Ref<boolean> = ref(false)
const messageInput: Ref<string> = ref('')
const messages = reactive<string[]>([])
let socket: WebSocket | null = null

// 初始化带ClientID的WebSocket
const initWebSocket = (): void => {
  const clientId = client_id.value
  console.log("initWebSocket");
  console.log(clientId);
  const wsUrl = `wss://${getDomainName()}/ws/minishop_order/pay_notify/${encodeURIComponent(clientId)}?client_id=${encodeURIComponent(clientId)}`
  
  socket = new WebSocket(wsUrl)

  socket.onopen = (event: Event) => {
    isConnected.value = true
    console.log('连接建立', event)
    sendSystemMessage('Connection established')
  }

  socket.onmessage = (event: MessageEvent<string>) => {
    try {
      const data = JSON.parse(event.data) as WebSocketMessage
      messages.push(`[${data.type}] ${data.content}`)
      const resData = JSON.parse(data.content);
      // 如果成功获取到 SUCCESS支付成功通知
      if (resData.code == 'SUCCESS') {
        //跳转到订单支付成功页

        // 跳转到订单支付成功页面
        openTabWithParams(order_id.value)

        if (resData.access_token) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
      


    } catch (error) {
      console.error('消息解析失败', error)
    }
  }

  socket.onerror = (event: Event) => {
    console.error('WebSocket错误:', event)
  }

  socket.onclose = (event: CloseEvent) => {
    isConnected.value = false
    console.log('连接关闭:', event)
    sendSystemMessage('Connection closed')
  }
}

// 发送系统消息（带ClientID）
const sendSystemMessage = (content: string): void => {
  if (!socket || socket.readyState !== WebSocket.OPEN) return
  
  const message: WebSocketMessage = {
    type: 'system',
    content,
    timestamp: Date.now(),
    clientId: client_id.value
  }
  socket.send(JSON.stringify(message))
}

function openTabWithParams(id: string) {
  // 这里就是路由跳转，也可以用path
  const params = { id: id };
  router.push(DEFAULT_HOME_PATH);
}

onMounted( async () => {
  //生成一个websocket客户端接收支付成功通知
  client_id.value = generateClientId();
  console.log(client_id.value);
currentDatas.value = minishopOrderRepo.value.all() as unknown as MinishopOrder[];
console.log(currentDatas.value);
console.log(queryParam.id);
const historyParams = history.state;
console.log(historyParams);
 if(historyParams.params?.id){
  order_id.value = String(historyParams.params.id);
  
  //需要在数据加载后初始化swiper。 Reinitialize Swiper after headimgs is updated

  //获取订单最终价格
  const orderData = {
      id:String(historyParams.params.id)
  }
  await useAxiosRepo(uctoo_minishop_order).api().handleOrderFinalPrice(orderData); //返回值自动更新models中订单数据

  //获取订单数据
  const res = minishopOrderRepo.value
    .query()
    .where('id',String(historyParams.params.id))
    .first();
  console.log('res', res); 
  currentRecord.value = res as unknown as MinishopOrder;

  if(currentRecord.value?.final_price){
    final_price.value = currentRecord.value?.final_price;
  }
  if(currentRecord.value?.ext_json){
    const ext_json = JSON.parse(currentRecord.value?.ext_json ?? '{}');
    if(ext_json?.minishop_order_detail){
      orderDetail.value = ext_json.minishop_order_detail;
      console.log('orderDetail', orderDetail.value); 
      
      if(orderDetail.value?.product_infos){
        product_infos.value = JSON.parse(orderDetail.value.product_infos ?? '{}');
        console.log('product_infos', product_infos.value); 
        if(product_infos.value){
          headimgs.value = product_infos.value[0]?.thumb_img ? JSON.parse(product_infos.value[0]?.thumb_img?? '[]') : [preferences.app.defaultAvatar];
          console.log('headimgs', headimgs.value); 
          order_title.value = product_infos.value[0]?.title ? product_infos.value[0]?.title : '订单名称';
        
        }
        console.log('descInfo', descInfo.value); 
      }
    }
  }
  

  nextTick(() => {
    new Swiper('.swiper', {
      direction: 'horizontal',
      loop: true,
      pagination: {
        el: '.swiper-pagination',
      },
      scrollbar: {
        el: '.swiper-scrollbar',
      },
    });
  });

  
  
  } /**/


  /* register();
  const swiper = document.querySelector('swiper-container');
  if (swiper) {
    swiper.initialize();
  } 
  const swiper = new Swiper('.swiper', {
  // Optional parameters
  direction: 'horizontal',
  loop: true,

  // If we need pagination
  pagination: {
    el: '.swiper-pagination',
  },

  // And if we need scrollbar
  scrollbar: {
    el: '.swiper-scrollbar',
  },
});*/
});
</script>

<template>
  <div class="p-4">
    <a-card :bordered="false">
      <a-empty v-if="!currentRecord" />
      <div v-else-if="currentRecord"  >
      
        <!-- Slider main container -->
        <a-row gutter="16">
          <!-- First Row -->
          <a-col :span="12">
            <!-- Swiper -->
            <div class="swiper">
              <div class="swiper-wrapper">
                <div 
                  v-for="(img, index) in headimgs" 
                  :key="index" 
                  class="swiper-slide"
                >
                  <img :src="img" alt="Product Image" class="product-image" />
                </div>
              </div>
              <div class="swiper-pagination"></div>
              <div class="swiper-scrollbar"></div>
            </div>
          </a-col>
          <a-col :span="12">
            <!-- Product Info -->
            <div>
              <h2>{{ order_title }}</h2>
              <h2>{{$t('database_column.minishop_order.out_order_id')}}:{{ currentRecord?.out_order_id }}</h2>
              <h3>{{ currentRecord?.subtitle }}</h3>
              <p>{{ currentRecord?.attrs }}</p>
              <p>¥{{ formatPrice(String(final_price)) }}元</p>
            </div>
            <div>
              <a-radio-group v-model:value="payOperator">
              <!--  <a-radio-button value="wechatpay">微信H5支付</a-radio-button>-->
                <a-radio-button value="wechatpayJSAPI">{{ $t('page.WechatPay') }}</a-radio-button>
                <a-radio-button value="alipay">{{ $t('page.alipay') }}</a-radio-button>
              </a-radio-group>
            </div>
            <!-- Product Actions -->
            <div class="product-actions">
              <!-- Quantity Selector -->
              <a-space>
              <!-- Action Buttons -->
              <div class="action-buttons">
                <a-space>
                  <a-button 
                type="primary" danger 
                  class="buy-now" 
                  @click="payOrder"
                >
                  {{$t('database_column.minishop_order.payOrder')}}
                </a-button>
                <a-button 
                  type="primary" 
                  class="add-to-cart" 
                  @click="cancelOrder"
                >
                {{$t('database_column.minishop_order.cancelOrder')}}
                  
                </a-button>
                
              </a-space>
              </div>
              </a-space>
            </div>
            <div>
              <vue-qrcode v-if="showPayQrCode"
                :value="payUrl"
                :options="qrOptions"
                type="image/png"
                :color="{ dark: qrOptions.colorDark, light: qrOptions.colorLight }"
              class="qrcode-box"
              />
              <span v-if="showPayQrCode && payOperator == 'wechatpayJSAPI'" class="text-muted-foreground">
                {{ $t('page.WechatScanQrCode') }}
              </span>
            </div>
          </a-col>
          <a-col :span="12">
            
          </a-col>
        </a-row>

        <!-- Second Row -->
        <a-row gutter="16" class="mt-4">
          <a-col :span="24">
            <!-- Product Detail Images -->
            <div v-for="(img, index) in descInfo" :key="index" class="detail-image">
              <img :src="img" alt="Detail Image" class="product-detail-image" />
            </div>
          </a-col>
        </a-row>
      </div><!--end Product detail -->
    </a-card>
  </div>
</template>
<style scoped>
.swiper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 320px;
  height: 320px;
  overflow: hidden;
}

.product-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.swiper-wrapper {
  display: flex;
}

.swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-actions {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.quantity-control {
  display: flex;
  gap: 5rpx;
  align-items: center;
  margin-top: 20rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  gap: 5rpx;
}

.qrcode-box {
  border: 1px solid #eee;
  padding: 10px;
  cursor: pointer;
  transition: transform 0.2s;
}

.qrcode-box:hover {
  transform: scale(1.00);
}
</style>
